/**
 * handle gateway device register request.
 */
var cmdCodes = require("../CmdCode/cmdCode.js");
var proto = require("../Proto/proto.js");
var dispatcher = require("../Dev/dispatcher.js");
var gateways = require("../Dev/gateways.js");
var redis = require("../Redis/redis.js");
var gatewayTable = require("../Redis/gatewayTable.js");

function onConnectionClosed(c) {
	"use strict";
	var devId = c.devId;
	if (!devId) {
		return;
	}
	
	console.error("gateway disconected:" + devId);
	
	gateways.del(devId);
	
	var context = {};
	redis.setClient(context);
	
	gatewayTable.setFields(context, devId, ["online", "false", "ip", ""]);
}

function registerHandler(cmd, c) {
	"use strict";
	var devId = cmd.devId;
	var gateway = gateways[devId];
	if (gateway) {
		c.destroy();
		return;
	}
	
	gateway = {};
	
	gateway.devId = devId;
	var reg = proto.parse(cmd.body, "CSGatewayReg");
	gateway.panId = reg.panId;
	gateway.description = reg.description;
	gateway.ip = c.remoteAddress;
	
	var context = {};
	redis.setClient(context);
	gatewayTable.add(context, gateway, function(err){
		if (err) {
			console.error("add gateway to redis failed:" + err);
			c.destroy();
		} else {
			console.error("gateway register ok:");
			console.error(gateway);
			
			gateway.c = c;
			gateways.addNew(gateway);
			
			c.devId = devId;
			c.isReady = true;
			c.dataHandler = dispatcher.defaultDataHandler;
			c.sendCommand = function(command, commandbody, type) {
				if (c.isReady) {
					var buf = proto.pack(command, commandbody, type);
					try {
						c.write(buf);
					} catch (e) {
						console.error("socket write exception:");
						console.error(e);
					}
				}
			};

			c.on("end", function(){
				c.isReady = false;
				onConnectionClosed(c);
			});
			
			// register reply
			c.sendCommand(cmd, {result:1}, "SCGetwayRegReply");
		}
	});
}

registerHandler.cmdCode = cmdCodes.CMD_GATEWAY_REGISTER;
module.exports = registerHandler;
